package com.zhanggm.springcloud.jpa.dao;

import com.zhanggm.springcloud.jpa.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private EntityManager entityManager;

    /**
     * 新增或修改
     * @param userEntity
     */
    @Transactional
    public void save(UserEntity userEntity){
        entityManager.merge(userEntity);
    }

    /**
     * 按Id查询
     * @param id
     * @return
     */
    public UserEntity findById(Integer id){
        UserEntity userEntity = entityManager.find(UserEntity.class, id);
        return userEntity;
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    public void del(Integer id){
        //先查询再删除
        UserEntity byId = findById(id);
        entityManager.remove(byId);
    }

    /**
     * 查询所有数据
     * @return
     */
    public List<UserEntity> findAll(){
        Query from_userEntity_u = entityManager.createQuery("from UserEntity u");
        List resultList = from_userEntity_u.getResultList();
        return resultList;
    }

    /**
     * 模糊查询
     * @param username
     * @return
     */
    public List<UserEntity> findByUsername(String username){
        Query from_userEntity_u = entityManager.createQuery("from UserEntity u where u.username like :username");
        from_userEntity_u.setParameter("username","%".concat(username).concat("%"));
        List resultList = from_userEntity_u.getResultList();
        Pageable pageable;
        return resultList;
    }
}
